package com.smart.manager.pop.repository;

import cn.hutool.core.lang.Assert;
import cn.hutool.core.lang.Opt;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSONObject;
import com.smart.common.entities.constant.SmartConstant;
import com.smart.common.entities.core.Page;
import com.smart.manager.member.entities.models.MemberProfileMain;
import com.smart.manager.member.entities.models.query.QMemberProfileMain;
import com.smart.manager.member.entities.views.MemberView;
import com.smart.manager.pop.entities.assembler.ShareData;
import com.smart.manager.pop.entities.body.RActivityAttend;
import com.smart.manager.pop.entities.models.PopActivityMain;
import com.smart.manager.pop.entities.models.PopBasicLink;
import com.smart.manager.pop.entities.models.PopC2cAttend;
import com.smart.manager.pop.entities.models.query.QPopBasicLink;
import com.smart.manager.pop.entities.models.query.QPopC2cAttend;
import com.smart.manager.pop.entities.views.ActivityMainView;
import com.smart.manager.system.repository.ConfigRepository;
import com.smart.service.poster.PosterService;
import com.smart.utils.MemberAcl;
import com.smart.utils.SqlUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

/**
 * 支付中心-订单管理
 *
 * @author Administrator
 */

@Log4j2
@Service
@RequiredArgsConstructor
public class ActivityAttendRepository {

    private final PosterService posterService;
    private final ConfigRepository configRepository;
    private final ActivityMainRepository activityMainRepository;

    /**
     * @param activityRegister 活动ID
     * @param memberId         会员编号
     * @param params           附加参数 格式 参数key =参数值
     * @return {@link PopC2cAttend}
     */
    public PopC2cAttend getActivityAttend(PopActivityMain activityRegister, Long memberId, String params) {
        Long activity = activityRegister.getId();
        ActivityMainView activityMainView = new ActivityMainView().setId(activity);
        PopC2cAttend record = new QPopC2cAttend().activity.eq(activityMainView).member.id.eq(memberId).setMaxRows(1).findOne();

        if (ObjUtil.isNotNull(record)) {
            return record;
        }
        Long linkId = activityRegister.getLinkId();
        PopBasicLink basicLink = new QPopBasicLink().id.eq(linkId).setMaxRows(1).findOne();
        Assert.notNull(basicLink, "活动链接信息不存在");
        //邀请地址 活动链接 邀请人链接  签名数据

        String shareUrl = String.format("%s?inviteMode=C2C&activityId=%s&inviteCode=%s", basicLink.getUrl(), activity, memberId);
        if (StrUtil.isNotBlank(params)) {
            shareUrl += "&" + params;
        }
        Long posterId = activityRegister.getPosterId();

        MemberProfileMain memberInfo = new QMemberProfileMain().id.eq(memberId).setMaxRows(1).findOne();
        //生成海报
        String posterUrl = posterService.makePosterImage(posterId, shareUrl, memberInfo);
        //获取分享数据
        ShareData shareData = new ShareData().setLink(shareUrl).setPoster(posterUrl).setThumb(basicLink.getThumb()).setDescription(basicLink.getDescription()).setTitle(basicLink.getTitle());
        //创建参与数据
        MemberView memberView = new MemberView().setId(memberId);

        PopC2cAttend attend = new PopC2cAttend().setAchievedTotal(0).setPrizeTotal(0).setActivity(activityMainView).setMember(memberView).setAttendTime(LocalDateTime.now()).setShareData(shareData);
        attend.save();
        return attend;
    }


    public Page<PopC2cAttend> pageList(RActivityAttend.SearchBody search) {
        QPopC2cAttend query = new QPopC2cAttend();
        Opt.ofNullable(search.getActivityId()).ifPresent(x -> query.activity.id.eq(x));
        Opt.ofBlankAble(search.getActivityTitle()).ifPresent(x -> query.activity.title.eq(x));

        Opt.ofBlankAble(search.getNickName()).ifPresent(x -> query.member.nickName.contains(x));
        Opt.ofBlankAble(search.getPhoneNumber()).ifPresent(x -> query.member.phoneNumber.eq(x));

        Opt.ofBlankAble(search.getDateRange()).ifPresent(x -> {
            LocalDateTime[] times = SqlUtil.formatDateTimeRange(x);
            query.attendTime.between(times[0], times[1]);

        });

        query.setFirstRow(search.firstRow()).setMaxRows(search.maxRows()).order().id.desc();
        return new Page<PopC2cAttend>().load(query.findPagedList());
    }


    /**
     * 获取猪仔分享海报
     *
     * @param pigCode 猪仔代码
     * @return {@link PopC2cAttend}
     */
    public PopC2cAttend getPigSharePoster(String pigCode, Long memberId) {
        JSONObject jsonObject = configRepository.readCache(SmartConstant.SHARE_CONFIG);
        long pigShareId = jsonObject.getLongValue("ActivityPIG");
        PopActivityMain activityRegister = activityMainRepository.getById(pigShareId);
        String params = "code=" + pigCode;
        return getActivityAttend(activityRegister, memberId, params);
    }


    /**
     * 创建分享海报 异步
     *
     * @param pigCode 猪仔代码
     */
    @Async
    public void setPigSharePoster(String pigCode, long memberId) {

        this.getPigSharePoster(pigCode, memberId);
    }


    /**
     * 获取会员分享海报
     */
    public PopC2cAttend getMemberSharePoster() {
        JSONObject jsonObject = configRepository.readCache(SmartConstant.SHARE_CONFIG);
        long plainShareId = jsonObject.getLongValue("ActivityC2C");
        PopActivityMain activityRegister = activityMainRepository.getById(plainShareId);
        //获取活动参与数据
        return getActivityAttend(activityRegister, MemberAcl.getLoginId(), null);
    }


}
